﻿using AppSocketModel;
using AppSocketService.Account;
using BCGPSCommon;
using BCGPSMongoData;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Text; 

namespace AppSocketService.Relay
{
    /// <summary>
    /// GPS数据转发
    /// </summary>
    public class RelayService : ServiceBase, IRelayService
    {
        private readonly MongoDBCommand<RelayDto> mongoCommand = new MongoDBCommand<RelayDto>("Relay");

        private readonly AccountDto CurrentAccount;
        private readonly IAccountService accountService; 


        public RelayService(IClaimsAccessor claimsAccessor, IAccountService accountService) : base(claimsAccessor)
        { 
            this.accountService = accountService;
            CurrentAccount = accountService.GetCurrentAccount(); 
        }

        public RelayService()
        { 
        }
        #region   添加转发
        public RelayDto Add(RelayRequestDto requestDto  )
        {
            var dto  = mongoCommand.SelectDocumentAsync(s => s.CompanyId == CurrentAccount.CompanyId).GetAwaiter().GetResult();

            if(dto==null)
            {
                RelayDto dtoNew = requestDto.As<RelayDto>();
                dtoNew.CompanyId = CurrentAccount.CompanyId;
                dtoNew.ModifyAccountCode = CurrentAccount.AccountCode;
                dtoNew.RelayControlCmdState = RelayControlCmdState.COMPLETE;
                dtoNew.RelayServerRunState = RelayServerRunState.STOP;
                dtoNew.Enable = true;
                dtoNew.ModifyTime = BCGPSCommon.MongoDBDateTime.GetNowUtc();
                mongoCommand.InsertDocumentAsync(dtoNew).GetAwaiter().GetResult();
            }
            else
            {
                RelayDto dtoNew = requestDto.As<RelayDto>();
                return Update(dtoNew);
            }

            return mongoCommand.SelectDocumentAsync(s => s.CompanyId == CurrentAccount.CompanyId).GetAwaiter().GetResult();
        }
        #endregion


        #region   添加转发
        public RelayDto Update(RelayDto updateDto)
        {
            var dto = mongoCommand.SelectDocumentAsync(s => s.CompanyId == CurrentAccount.CompanyId).GetAwaiter().GetResult();

            if (dto == null)
            {
                throw new ArgumentException("修改失败,要修改的记录不存在!");
            }
            else
            {
                var update = Builders<RelayDto>.Update
                    .Set(s => s.ModifyAccountCode, CurrentAccount.AccountCode)
                    .Set(s => s.ModifyTime, BCGPSCommon.MongoDBDateTime.GetNowUtc())
                    .Set(s => s.RelayUrl, updateDto.RelayUrl)
                    .Set(s => s.Port, updateDto.Port)
                    .Set(s=>s.RelayType,updateDto.RelayType)
                    .Set(s => s.ImeiList, updateDto.ImeiList);
                var ret = mongoCommand.UpdateDocumentAsync(s => s.CompanyId == CurrentAccount.CompanyId, update).GetAwaiter().GetResult();
                if (ret == null)
                    throw new ArgumentException("修改失败,请重试!");
            }

            return mongoCommand.SelectDocumentAsync(s => s.CompanyId == CurrentAccount.CompanyId).GetAwaiter().GetResult();
        }
        #endregion

        #region 删除
        public bool Delete()
        {
            return mongoCommand.DeleteDocumentAsync(s => s.CompanyId == CurrentAccount.CompanyId).GetAwaiter().GetResult().DeletedCount>0;
        }
        #endregion

        public RelayDto Get()
        {
            return mongoCommand.SelectDocumentAsync(s => s.CompanyId == CurrentAccount.CompanyId).GetAwaiter().GetResult();
        }

        public List<RelayDto> GetAll()
        {
            return mongoCommand.SelectDocumentsAsync(s => s.Enable == true).GetAwaiter().GetResult();
        }

        public List<RelayDto> GetNewCommond()
        {
            return mongoCommand.SelectDocumentsAsync(s => s.RelayControlCmdState == RelayControlCmdState.NEW && s.Enable == true).GetAwaiter().GetResult();
        }

        public List<RelayDto> GetRunningCommond()
        {
            return mongoCommand.SelectDocumentsAsync(s => s.RelayControlCmdState == RelayControlCmdState.RUNNING && s.Enable == true).GetAwaiter().GetResult();
        }

        public RelayDto GetByCompanyId(int companyId)
        {
            return mongoCommand.SelectDocumentAsync(s => s.CompanyId == companyId).GetAwaiter().GetResult();
        }

        public bool SendControlCmd(RelayServerRunState relayServerRunState)
        {
            SetCmdRunState(CurrentAccount.CompanyId,RelayControlCmdState.NEW);
            return SetServerRunState(CurrentAccount.CompanyId, relayServerRunState); 
        }

        public bool SetCmdRunState(int companyId,RelayControlCmdState relayControlCmdState)
        {
            var update = Builders<RelayDto>.Update.Set(s => s.RelayControlCmdState, relayControlCmdState); 
            var ret = mongoCommand.UpdateDocumentAsync(s => s.CompanyId == companyId, update).GetAwaiter().GetResult();
            if (ret == null)
                return false;
            else
            return true;
        }
        public bool SetServerRunState(int companyId, RelayServerRunState  relayServerRunState)
        {
            var update = Builders<RelayDto>.Update.Set(s => s.RelayServerRunState, relayServerRunState);
            var ret = mongoCommand.UpdateDocumentAsync(s => s.CompanyId == companyId, update).GetAwaiter().GetResult();
            if (ret == null)
                return false;
            else
                return true;
        }
        public bool SetLastError(int companyId, string ErrorMsg)
        {
            var update = Builders<RelayDto>.Update
                .Set(s => s.LastErrorMessage, ErrorMsg)
                .Set(s=>s.LastErrorTime,BCGPSCommon.MongoDBDateTime.GetNowUtc());
            var ret = mongoCommand.UpdateDocumentAsync(s => s.CompanyId == companyId, update).GetAwaiter().GetResult();
            if (ret == null)
                return false;
            else
                return true;
        }
    }
}
